package com.dacool.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.json.JSONObject;

import android.util.Base64;

public class SignatureTool {
	private static final String HMAC_SHA1 = "HmacSHA1";
	private static final String UTF8 = "utf-8";
	private static final String APP_SECRET = "citylife@2013#ec";

	public static String signature(String method, String url,
			HashMap<String, String> params) throws UnsupportedEncodingException {
		String ret = "";
		String bss = method + "&" + URLEncoder.encode(url, UTF8) + "&";
		Collection<String> keyset = params.keySet();
		List<String> list = new ArrayList<String>(keyset);
		Collections.sort(list);
		String bsss = "";
		for (int i = 0; i < list.size(); i++) {
			String key = list.get(i);
			bsss += key + "=" + params.get(key) + "&";
		}
		bsss = bsss.substring(0, bsss.length() - 1);
		bsss = URLEncoder.encode(bsss, UTF8).replace("+", "%20");
		String data = bss + bsss;
		ret = URLEncoder.encode(hmacsha1(data, APP_SECRET), UTF8);

		return ret;
	}

	public static String signature(String method, String url,
			JSONObject jsonObject) throws UnsupportedEncodingException {
		String ret = "";
		String bss = method + "&" + URLEncoder.encode(url, UTF8) + "&";

		List<String> list = new ArrayList<String>();
		for (@SuppressWarnings("unchecked")
		Iterator<String> iterator = jsonObject.keys(); iterator.hasNext();) {
			String key = iterator.next();
			list.add(key);
		}
		Collections.sort(list);
		String bsss = "";
		for (int i = 0; i < list.size(); i++) {
			String key = list.get(i);
			bsss += key + "=" + jsonObject.opt(key) + "&";
		}
		bsss = bsss.substring(0, bsss.length() - 1);
		bsss = URLEncoder.encode(bsss, UTF8).replace("+", "%20");
		String data = bss + bsss;
		ret = hmacsha1(data, APP_SECRET);

		return ret;
	}

	public static String hmacsha1(String data, String key) {
		byte[] byteHMAC = null;
		try {
			Mac mac = Mac.getInstance("HmacSHA1");
			SecretKeySpec spec;
			try {
				spec = new SecretKeySpec(key.getBytes(UTF8), HMAC_SHA1);
				mac.init(spec);
				byteHMAC = mac.doFinal(data.getBytes());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException ignore) {
		}
		String oauth = Base64.encodeToString(byteHMAC, Base64.DEFAULT);
		return oauth;
	}
}
